import React, {useContext, useEffect, useState} from 'react';
import { Modal, StyleSheet, Alert, View, PermissionsAndroid, Platform } from 'react-native';
import { Text } from 'react-native-elements';
import Toast from 'react-native-simple-toast';

import {getVersion, getVersion2} from "./../libs/nodes";
import RNFetchBlob from 'rn-fetch-blob'
const pkg = require('../package.json');

import {ProgressBar} from '@react-native-community/progress-bar-android';
import RNApkInstallerN from 'react-native-apk-installer-n';
import LocaleContext from "../libs/locale";
import WalletContext from "../libs/wallet";

export interface Props {
    startDownload?: string;
}

const UpdateView: React.FC<Props> = ({startDownload}: Props) => {

    const [storagePermission, setStoragePermission] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [progressNumber, setProgressNumber] = useState(0);
    const startDownloading = startDownload;
    const wallet: any = useContext(WalletContext);
    const locale = useContext(LocaleContext);

useEffect(()=>{
    const work = async () =>{
      if(Platform.OS === 'android'){
        requestPermissionFunction();
        console.log("UpdateView ----->>> Props.startDownload ====>>>> "+startDownloading);
        if(parseInt(startDownloading + '') > 0){
            console.log("downloadAPKForInstall ----->>> Props.startDownload ====>>>> "+startDownloading);
            try{
                const ht = await downloadAPKForInstall();
            }catch(e){
                console.log("downloadAPKForInstall error === >>>>" + e);
            }
          }
        }else if(Platform.OS === 'ios'){
        }
    };
    work();
},[startDownloading]);

//获取Android 读写SD权限;
const requestPermissionFunction = async() =>
{
    try {
        const permissions = [
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        ];
        const granteds = await PermissionsAndroid.requestMultiple(permissions);
        if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
            setStoragePermission(true);
        } else {
            setStoragePermission(false);
            Alert.alert("请先开启权限！");
        }
        return storagePermission;
    } catch (err) {
       console.log(err);
    }
}

//TODO 更新下载
const downloadAPKForInstall = async() => {
    if(storagePermission)
    {
      marchAndDownloadingForInstall();
    }else{
      requestPermissionFunction();
    }
};

 //TODO 匹配本地appversion 并且 下载安装
 const marchAndDownloadingForInstall = async() => {
     try {
         const newVersion = await getVersion(pkg.version,wallet.address);
         console.log("checkAppVersion ===>>>>   " + JSON.stringify(newVersion));
         // if(!isNaN(newVersion.dict.version)){
         console.log("newVersion.dict.version ===>>>>   " + newVersion.dict.version + ' pkg.version: ' + pkg.version);
         if (checkAppVersion(newVersion.dict.version, pkg.version)) {
             Alert.alert('', locale?._('checkNewversion'), [{
                 text: locale?._('cancel'),
                 onPress: () => console.log("Cancel Pressed"),
                 style: "cancel"
             }, {
                 text: locale?._('ok'), onPress: () => {
                     setModalVisible(true);
                     downloadAPKFile(newVersion.dict.url);
                 }
             }]);
         } else {
             Toast.show(locale?._('isNewVersion') as string)
         }
     }
     catch (e) {
         console.log("检查出错了"+e)
         Toast.show(locale?._('isNewVersion') as string)
     }
      // }
  }

  //下载APK文件;
  const downloadAPKFile = async (dictUrl:any) =>
  {
      // dictUrl="http://192.168.1.102/SATApp-rel-1.2.1.apk"
      // dictUrl = "http://192.168.1.102/SATApp-rel-3.0.1.apk";
      // dictUrl = "http://198.245.49.104/SATApp-rel-3.0.1.apk";
      console.log('更新下载链接==》'+dictUrl)
    const downloadAndroid = await RNFetchBlob.android
    RNFetchBlob.config(
    {
      fileCache : true,
      // path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
      //   addAndroidDownloads : {
      //   useDownloadManager : true,
      //   title : 'awesome.apk',
      //   description : 'An APK that will be installed',
      //   mime : 'application/vnd.android.package-archive',
      //   path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
      //   mediaScannable : true,
      //   notification : true,
      // }
    })
    .fetch('GET', dictUrl, {
        //... some headers,
        // 'Content-Type' : 'octet-stream'
    })
    .progress({count:100},(received,total) => {
      setProgressNumber((Math.round((received / total) * 100)));
      // Toast.show((Math.round(received / total  * 100)).toString(),0.1)
      console.log((Math.round(received / total * 100)).toString())
    })
    // .then((res) => {
    //   downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive'), RNFetchBlob.fs.scanFile([{path:res.path(),mime:'apk'}])
    // })
    .then((res) => {
      setModalVisible(false);
    //   downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
      RNApkInstallerN.install(res.path());
    })
    .catch((err)=>{
      setModalVisible(false);
        Toast.show("请重新点击")
      console.log('downloadAPKForInstall err: ' + err);
    });
  }

  //检查是否有新的版本;
  const checkAppVersion = (serverVersionCode:any,localVersionCode:any) => {
    try{
      const currentVersionCode = formatVersionCode(localVersionCode);
      const newsVersionCode = formatVersionCode(serverVersionCode);
      console.log('checkAppVersion  localVersionCode: ' + currentVersionCode + ' newsVersionCode: ' + newsVersionCode);
      if(parseInt(currentVersionCode) < parseInt(newsVersionCode)){
        return true;
      }
    }catch(error){
      console.log(error);
    }
    return false;
  }

  //TODO  格式化VersionCode
  const formatVersionCode = (versionCode:any)=>{
    return versionCode.replace('.','').replace('.','');
  }

   return (
     <View>
      <Modal
            animationType='fade'
            statusBarTranslucent={true}
            transparent={true}
            visible={modalVisible}
            onRequestClose={()=>{
              setModalVisible(!modalVisible);
              // Alert.alert("Modal has been closed.");
            }}>
            <View style={styles.progressBarView}>
                <View style={styles.subView}>
                    <Text style={styles.title}>
                        {"正在下载,请稍后..."}
                    </Text>
                    <ProgressBar
                      color="black"
                      styleAttr="Horizontal"
                      indeterminate={false}
                      progress={
                        progressNumber / 100
                    }/>
                    <View style = { styles.progressContainer }>
                        <Text style = { styles.progressLeftText }>
                            {
                              progressNumber
                            }%
                        </Text>
                        <Text style={styles.progressRightText}>
                          {
                              100
                          }%
                        </Text>
                    </View>
                </View>
            </View>
        </Modal>
     </View>
  );
};

const styles = StyleSheet.create({
  progressBarView: {
      flex:1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'rgba(0,0,0,0.2)',
  },
  progressLeftText: {
      fontSize: 14
  },
  cancleContainer: {
      justifyContent: 'center',
      alignItems: 'flex-end'
  },
  progressRightText: {
      fontSize: 14,
      color: '#666666'
  },
  barBackgroundStyle: {
      backgroundColor: '#cccccc'
  },
  progressContainer: {
      flexDirection: 'row',
      padding: 10,
      justifyContent: 'space-between'
  },
  subView: {
      marginLeft: 30,
      marginRight: 30,
      paddingLeft:10,
      paddingRight:10,
      backgroundColor: '#fff',
      alignSelf: 'stretch',
      justifyContent: 'center',
      borderRadius:20,
  },
  progressView: {
      flexDirection: 'row',
      padding: 10,
      paddingBottom: 5,
      justifyContent: 'space-between'
  },
  title: {
      textAlign: 'left',
      padding:10,
      fontSize: 16
  },
  cancleButton: {
      padding:10
  },
  cancleText: {
      textAlign: 'right',
      paddingTop: 0,
      fontSize: 16,
      color: 'rgba(0, 122, 255, 1)'
  },
});

export default UpdateView;
